﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Batman.Core
{
    public static class RequestExtension
    {
        public static Dictionary<string, object> ToDictionary(this QueryString queryString)
        {
            var dict = new Dictionary<string, object>();

            if (!queryString.HasValue) return dict;

            // todo: 写单元测试
            foreach (var item in queryString.Value.Split('&'))
            {
                var matched = Regex.Match(item, @"(?<key>[_a-zA-Z0-1]+?)=(?<value>[\S\s]+)");
                if (!matched.Success) continue;

                var key = matched.Groups["key"].Value;
                var val = matched.Groups["value"].Value;

                var results = new List<object>();


                foreach (var item2 in val.Split(','))
                {
                    object value = item2;

                    if (item2.IndexOf(".") > -1)
                    {
                        if (double.TryParse(item2, out var doubleVal)) value = doubleVal;
                    }
                    else
                    {
                        if (int.TryParse(item2, out var intVal)) value = intVal;
                        else if (long.TryParse(item2, out var longVal)) value = longVal;
                    }

                    if (DateTime.TryParse(item2, out var datetimeVal)) value = datetimeVal;

                    results.Add(value);
                }

                if (dict.ContainsKey(key))
                {
                    dict[key] = new List<object>();
                }
                else
                {
                    dict.Add(key, results.Count > 1 ? results : results.FirstOrDefault());
                }
            }

            return dict;

        }
    }
}
